const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TokenSchema = new Schema({
  'name': {
    type: String,
    default: 'access_token'
  },
  'token': {
    type: String,
    required: true,
    trim: true
  },
  expires_in: {
    type: Number,
    required: true
  },
  meta: {
    createdAt: {
      type: Number,
      default: new Date().valueOf()
    },
    updatedAt: {
      type: Number,
      default: new Date().valueOf()
    }
  }
});
TokenSchema.pre('save', function (next) {
  // do stuff
  if (this.isNew) {
    this.meta.createdAt = this.meta.updatedAt = new Date().valueOf()
  } else {
    this.meta.updatedAt = new Date().valueOf()
  }
  next();
});
TokenSchema.statics = {
  async getAccessToken() {
    const token = await this.findOne({
      name: 'access_token'
    }, {
      _id: 0,
      meta: 0
    })
    if (token && token.token) {
      token.access_token = token.token;
    }
    return token;
  },
  async saveAccessToken(data) {
    let token = await this.findOne({
      name: 'access_token'
    })
    if (!token) {
      token = new Token({
        'name': 'access_token',
        'token': data['access_token'],
        'expires_in': data['expires_in']
      })
    } else {
      token['expires_in'] = data['expires_in'];
      token.token = data['access_token'];
    }
    await token.save()
    return data;
  }
}

const Token = mongoose.model('Token', TokenSchema, 'token');
